package cn.earas.ip.netdata;

import java.io.IOException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.gargoylesoftware.htmlunit.ScriptResult;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

import cn.earas.ip.Data;

public class IPGet_66 implements Runnable {

	Header[] cookie;

	private void getIP(CloseableHttpClient httpClient) {
		final HttpGet get = new HttpGet(
				"http://www.66ip.cn/mo.php?sxb=&tqsl=1000&ports%5B%5D2=&ktip=&sxa=&radio=radio&submit=%CC%E1++%C8%A1");
		get.setHeader("Host", "www.66ip.cn");
		get.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0");
		get.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		get.setHeader("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
		get.setHeader("Accept-Encoding", "gzip, deflate");
		get.setHeader("Connection", "keep-alive");
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(3000)// 一、连接超时：connectionTimeout-->指的是连接一个url的连接等待时间
				.setSocketTimeout(3000)// 二、读取数据超时：SocketTimeout-->指的是连接上一个url，获取response的返回等待时间
				.setConnectionRequestTimeout(3000).build();
		get.setConfig(requestConfig);
		try {
			HttpResponse resp = httpClient.execute((HttpUriRequest) get);
			cookie = resp.getHeaders("Set-Cookie");
		} catch (ClientProtocolException e2) {
			System.out.println("66IP获取Cookie失败");
		} catch (IOException e3) {
			System.out.println("66IP获取Cookie失败");
		}
	}

	private void getIP1(CloseableHttpClient httpClient) {
		try {
			URL link = new URL(
					"http://www.66ip.cn/mo.php?sxb=&tqsl=1000&ports%5B%5D2=&ktip=&sxa=&radio=radio&submit=%CC%E1++%C8%A1");
			WebRequest request = new WebRequest(link);
			request.setCharset(Charset.forName("UTF-8"));
			request.setAdditionalHeader("Referer",
					"http://www.66ip.cn/mo.php?sxb=&tqsl=1000&ports%5B%5D2=&ktip=&sxa=&radio=radio&submit=%CC%E1++%C8%A1");// 设置请求报文头里的refer字段
			request.setAdditionalHeader("User-Agent",
					"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0");
			WebClient wc = new WebClient();
			wc.getCookieManager().setCookiesEnabled(true);// 开启cookie管理
			wc.getOptions().setJavaScriptEnabled(true);// 开启js解析。对于变态网页，这个是必须的
			wc.getOptions().setCssEnabled(false);// 关闭css解析。
			wc.getOptions().setThrowExceptionOnFailingStatusCode(false);
			wc.getOptions().setThrowExceptionOnScriptError(false);
			wc.getOptions().setRedirectEnabled(true);
			wc.getOptions().setTimeout(5000);
			wc.setJavaScriptTimeout(5000);
			for (int i = 0; i < cookie.length; i++) {
				Header ck = cookie[i];
				com.gargoylesoftware.htmlunit.util.Cookie ucookies = new com.gargoylesoftware.htmlunit.util.Cookie(
						"www.66ip.cn", ck.getName(), ck.getValue());
				wc.getCookieManager().addCookie(ucookies);
			}

			HtmlPage hp = wc.getPage(request);
			String body = hp.getBody().asXml();
			// 截取js函数
			String function = body.substring(body.indexOf("function"), body.lastIndexOf("}") + 1);
			// 把设置cookie的函数替换成返回
			function = function.replace("eval(\"qo=eval;qo(po);\")", "return po");
			// 提取js函数参数(正则表达式匹配)
			String regx = "setTimeout\\(\\\"\\D+\\((\\d+)\\)\"";
			Pattern pattern = Pattern.compile(regx);
			Matcher matcher = pattern.matcher(body);
			String call = "";
			while (matcher.find()) {
				String group = matcher.group();
				call = group.substring(group.indexOf("\"") + 1, group.lastIndexOf("\""));
			}
			ScriptResult ckstr = hp.executeJavaScript(function + call);
			String cookie = ckstr.getJavaScriptResult().toString();
			cookie = cookie.substring(cookie.indexOf("'") + 1, cookie.indexOf(";") + 1);
			getIP2(httpClient, cookie);
			wc.close();
		} catch (ClientProtocolException e2) {
			System.out.println("66IP解密Js失败");
		} catch (IOException e3) {
			System.out.println("66IP解密Js失败");
		}
	}

	private void getIP2(CloseableHttpClient httpClient, String cookie) {
		final HttpGet get = new HttpGet(
				"http://www.66ip.cn/mo.php?sxb=&tqsl=1000&ports%5B%5D2=&ktip=&sxa=&radio=radio&submit=%CC%E1++%C8%A1");
		get.setHeader("Host", "www.66ip.cn");
		get.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0");
		get.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		get.setHeader("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
		get.setHeader("Accept-Encoding", "gzip, deflate");
		get.setHeader("Connection", "keep-alive");
		get.setHeader("Referer",
				"http://www.66ip.cn/mo.php?sxb=&tqsl=1000&ports%5B%5D2=&ktip=&sxa=&radio=radio&submit=%CC%E1++%C8%A1");
		get.setHeader("Cookie", cookie);
		try {
			final HttpEntity entity = httpClient.execute((HttpUriRequest) get).getEntity();
			String result = EntityUtils.toString(entity);
			if (result.contains("<br />")) {
				Matcher m = Pattern.compile(Data.REG).matcher(result);
				while (m.find()) {
					String data = m.group(1);
					if (!Data.ips.contains(data))
						Data.ips.add(data);
				}
			}
		} catch (ClientProtocolException e2) {
			System.out.println("66IP\u83b7\u53d6\u5931\u8d25\uff01");
		} catch (IOException e3) {
			System.out.println("66IP\u83b7\u53d6\u5931\u8d25\uff01");
		}
	}

	@Override
	public void run() {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		getIP(httpClient);
		getIP1(httpClient);
		try {
			if (httpClient != null)
				httpClient.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
